package org.example.controller;


import org.example.exception.AppException;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController //什么意思呢？就是Controller加上ResponseBody
@RequestMapping("/user")
public class UserController {
    @Autowired //这里是注入usermapper
    private UserService userService;

    @RequestMapping("/login")
    public Object login(User user, HttpServletRequest req){
        //构造返回的数据
        Map<String,Object> json = new HashMap<>();
        //验证账号密码
        //这里写个假数据就行，就不涉及到数据库了
        if("a".equals(user.getUsername()) && "123".equals(user.getPassword())){
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            json.put("ok",true);
        }else{
            throw new AppException("用户名或者密码出错");
        }
        return json;

    }

    @RequestMapping("/insert")
    public Object insert(User user){//支持 queryString 表单  from-data  写成json的话会以网页的形式返回
        int n = userService.insert(user);
        return n;
    }

    @RequestMapping("/delete")
    public Object delete(int id){
        int n = userService.delete(id);
        return n;
    }

    @RequestMapping("/update")
    public Object update(User user){
        int n = userService.update(user);
        return n;
    }


    @RequestMapping("/all")
    public Object selectall(){
        List<User> users = userService.add();
        return users;
    }

    @RequestMapping("/select/{id}")
    public Object select(@PathVariable int id){
        User user  = userService.select(id);
        return user;
    }
    @RequestMapping("/select/orderBy")
    public Object selectOrderBy(String orderBy){
        List<User> users = userService.selectOrderBy(orderBy);
        return users;
    }

    @RequestMapping("/select/like")
    public Object selectLike(String username){
        List<User> users = userService.selectLike(username);
        return users;
    }

    @RequestMapping("/select/duoyu")
    public Object selectDuoyu(){
        List<User> users = userService.selectDuoyu();
        return users;
    }

    @RequestMapping("/select/users")
    public Object selectUsersAndArticles(){
        List<User> users = userService.selectUsersAndArticles();
        return users;
    }
}
